package by.grsu.pereverzev.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;



import by.grsu.pereverzev.entity.Application;
import by.grsu.pereverzev.entity.Bill;
import by.grsu.pereverzev.table.BillTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class BillDao extends AbstractDao<BillTable, Bill> {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 276084035702344018L;

	public BillDao(final String rootFolderPath) {
		super(rootFolderPath);
	}


	public List<Bill> getByPassengerId(Long id) {
		List<Bill> result = new ArrayList<Bill>();
		List<Bill> all = getAll();
		for (Bill bill : all) {
			if (bill.getPayerId().equals(id)) {
				result.add(bill);
			}
		}
		return result;
	}
	
	@Override
	public Long saveNew(final Bill newBill) {
		// set ID
		Long nextId = getNextId();
		newBill.setId(nextId);
		// get existing data
		final BillTable billTable = deserializeFromXml();
		// add new row
		billTable.getRows().add(newBill);
		// save data
		serializeToXml(billTable);
		return nextId;
	}

	@Override
	public void update(final Bill entity) {
		// get existing data
		final BillTable billTable = deserializeFromXml();
		// find by ID
		for (final Bill row : billTable.getRows()) {
			if (row.getId().equals(entity.getId())) {
				// found!!!
				// copy data
				row.setId(entity.getId());
				row.setPayed(entity.isPayed());
				row.setPayerId(entity.getPayerId());
				row.setValue(entity.getValue());
				break;
			}
		}
		// save updated table
		serializeToXml(billTable);
	}

	@Override
	public Bill get(final Serializable id) {
		// get existing data
		final BillTable billTable = deserializeFromXml();
		// find by ID
		for (final Bill row : billTable.getRows()) {
			if (row.getId().equals(id)) {
				return row;
			}
		}
		return null;
	}
	
	@Override
	public List<Bill> getAll() {
		// get existing data
		final BillTable billTable = deserializeFromXml();
		return billTable.getRows();
	}
	
	@Override
	public void delete(final Serializable id) {
		// get existing data
		final BillTable billTable = deserializeFromXml();
		// find by ID
		Bill toBeDeleted = null;
		for (final Bill row : billTable.getRows()) {
			if (row.getId().equals(id)) {
				// found!!!
				toBeDeleted = row;
				break;
			}
		}
		// remove from list
		billTable.getRows().remove(toBeDeleted);
		// save updated table
		serializeToXml(billTable);
	}

	@Override
	protected Class<BillTable> getTableClass() {
		return BillTable.class;
	}



}
